package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.exception.ServiceException;
import cn.tedu.csmall.commons.pojo.vo.PageData;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.BrandMapper;
import cn.tedu.csmall.product.mapper.SPUMapper;
import cn.tedu.csmall.product.pojo.entity.BrandCategory;
import cn.tedu.csmall.product.pojo.entity.Brand;
import cn.tedu.csmall.product.pojo.entity.SPU;
import cn.tedu.csmall.product.pojo.param.BrandInsertParam;
import cn.tedu.csmall.product.pojo.param.BrandUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.BrandListVO;
import cn.tedu.csmall.product.pojo.vo.BrandStandardVO;
import cn.tedu.csmall.product.service.BrandService;
import cn.tedu.csmall.commons.util.PageDataConverter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    BrandMapper mapper;
    @Autowired
    SPUMapper spuMapper;
    @Autowired
    BrandCategoryMapper brandCategoryMapper;
    @Override
    public void insert(BrandInsertParam brandInsertParam) {
        log.debug("开始处理【添加品牌】的业务，参数：{}",brandInsertParam);
        QueryWrapper<Brand> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",brandInsertParam.getName());
        int countByName = mapper.selectCount(queryWrapper);
        log.debug("根据品牌名称统计匹配的品牌数量，结果：{}", countByName);
        if(mapper.selectCount(queryWrapper)>0){
            String message="添加品牌失败，品牌名称已被占用!";
            log.warn(message);
            throw new ServiceException(message, ServiceCode.ERR_CONFLICT);
        }


        Brand brand=new Brand();
        BeanUtils.copyProperties(brandInsertParam,brand);
        brand.setSales(0);
        brand.setProductCount(0);
        brand.setCommentCount(0);
        brand.setPositiveCommentCount(0);
        brand.setGmtCreate(LocalDateTime.now());
        brand.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的品牌数据写入到数据库，数据：{}", brand);
        int row = mapper.insert(brand);
        if(row !=1){
            String message="添加管理员失败，服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException(message, ServiceCode.ERR_INSERT);
        }
        log.debug("将新的品牌数据写入到数据库，完成！");
    }

    @Override
    public void deleteById(Long brandId) {
        log.debug("开始处理【删除品牌】的业务，参数：{}", brandId);
        // 检查品牌是否存在，如果不存在，则抛出异常
        QueryWrapper<Brand> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", brandId);
        int countById = mapper.selectCount(queryWrapper1);
        log.debug("根据品牌ID统计匹配的品牌数量，结果：{}", countById);
        if (countById == 0) {
            String message = "删除品牌失败，品牌数据不存在！";
            log.warn(message);
            throw new ServiceException(message,ServiceCode.ERR_NOT_FOUND);
        }
        //检查是否有分类关联此品牌
        QueryWrapper<BrandCategory> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("brand_id",brandId);
        int countByBrandId2 = brandCategoryMapper.selectCount(queryWrapper2);
        log.debug("根据品牌ID统计匹配的品牌数量，结果：{}", countByBrandId2);
        if(countByBrandId2>0){
            String message="删除品牌失败，仍有分类关联此品牌!";
            log.warn(message);
            throw new ServiceException(message,ServiceCode.ERR_CONFLICT);
        }

        //检查是否有SPU关联此品牌
        QueryWrapper<SPU> queryWrapper3=new QueryWrapper<>();
        queryWrapper3.eq("brand_id",brandId);
        int countByBrandId3 = spuMapper.selectCount(queryWrapper3);
        log.debug("根据品牌ID统计匹配的品牌数量，结果：{}", countByBrandId3);
        if(countByBrandId3>0){
            String message="删除品牌失败，仍有spu关联此品牌!";
            log.warn(message);
            throw new ServiceException(message,ServiceCode.ERR_CONFLICT);
        }
        int row = mapper.deleteById(brandId);
        if(row !=1){
            String message="添加管理员失败，服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException( message,ServiceCode.ERR_DELETE);
        }
    }

    @Override
    public void update(BrandUpdateInfoParam brandUpdateInfoParam) {
        log.debug("开始处理【修改品牌】的业务，参数：{}", brandUpdateInfoParam);
        QueryWrapper<Brand> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", brandUpdateInfoParam.getId());
        int countById = mapper.selectCount(queryWrapper1);
        log.debug("根据品牌ID统计匹配的品牌数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改品牌失败，品牌数据不存在！";
            log.warn(message);
            throw new ServiceException(message,ServiceCode.ERR_NOT_FOUND);
        }

        QueryWrapper<Brand> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",brandUpdateInfoParam.getName())
                .ne("id",brandUpdateInfoParam.getId());
        int countByName = mapper.selectCount(queryWrapper);
        log.debug("根据品牌名称统计匹配的品牌数量，结果：{}", countByName);
        if(mapper.selectCount(queryWrapper)>0){
            String message="修改品牌失败，品牌名称已被占用!";
            log.warn(message);
            throw new ServiceException(message,ServiceCode.ERR_CONFLICT);
        }
        

        
        
        Brand brand=new Brand();
        BeanUtils.copyProperties(brandUpdateInfoParam,brand);

        int row = mapper.updateById(brand);
        if(row !=1){
            String message="添加管理员失败，服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException(message, ServiceCode.ERR_UPDATE);
        }
    }

    @Override
    public BrandStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询品牌】的业务，参数：{}", id);
        if(mapper.getStandardById(id)==null){
            String message = "查询品牌详情失败，品牌数据不存在！";
            log.warn(message);
            throw new ServiceException(message,ServiceCode.ERR_NOT_FOUND);
        }
        return mapper.getStandardById(id);
    }

    @Override
    public PageData<BrandListVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询品牌】的业务，页数：{}，每页的数据量：{}",pageNum,pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<BrandListVO> list=mapper.list();
        PageInfo<BrandListVO> pageInfo=new PageInfo<>(list);
        PageData<BrandListVO> pageData= PageDataConverter.convert(pageInfo);
        return pageData;
    }

    @Override
    public PageData<BrandListVO> list(Integer pageNum) {
        Integer pageSize=5;
        return list(pageNum,pageSize);
    }
}
